import router from "@/router";
import store from "@/store";
import ACCESS_ENUM from "./accessEnum";
import checkAccess from "./checkAccess";

router.beforeEach(async (to,from,next)=>{
    console.log("用户登录信息",store.state.user.loginUser);

    let loginUser=store.state.user.loginUser;
   
    //如果之前没有登录过，自动登录
    if(!loginUser || !loginUser.userRole){
      //加await是为了等用户登录成功之后，再执行后续代码
      await store.dispatch("user/getLoginUser");
      loginUser=store.state.user.loginUser;
    }
   
    const needAccess=(to.meta?.access as string) ?? ACCESS_ENUM.NOT_LOGIN;
    //如果你要跳转到的页面必须要用户或管理员权限
    if(needAccess !==ACCESS_ENUM.NOT_LOGIN){
      //如果你还没有登录的话，请先登录
      if(!loginUser || !loginUser.userRole || loginUser.userRole === ACCESS_ENUM.NOT_LOGIN){
        const fullPath=to.fullPath;
        next("/user/login?redirect="+fullPath);
        return;
      }
      //如果你已经登录了，但是你要跳转到的页面比你的userRole权限要大，跳转到无权限界面
      if(!checkAccess(loginUser,needAccess)){
        next("/noAuth");
        return;
      }
    }
    //其余的情况直接跳转到点击的页面即可
    next();
 });
 